package com.suma.platform.core.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Preconditions;
import com.suma.platform.core.enums.ResultCode;
import com.suma.platform.core.mapper.UserMapper;
import com.suma.platform.core.model.User;
import com.suma.platform.core.model.UserExample;
import com.suma.platform.core.model.qo.WechatUserQO;

import lombok.extern.slf4j.Slf4j;

/**
 * @author suma
 * @date 2018/1/10 下午1:49
 */
@Slf4j
@Component
@Transactional
@CacheConfig(cacheNames = "HALF_HOUR")
public class WechatUserService {

	@Autowired
	UserMapper userMapper;

	/**
	 * 根据openid查询微信用户信息
	 *
	 * @param [openid]
	 *            微信openid
	 * @return WechatUser
	 */
	@Cacheable(value = "ONE_MINUTE", key = "#openid")
	public User getWechatUserByOpenid(String openid) {
		Preconditions.checkNotNull(openid, ResultCode.OPENID_NULL.getDesc());
		UserExample example = new UserExample();
		example.createCriteria().andOpenidEqualTo(openid);
		List<User> wechatUserList = userMapper.selectByExample(example);
		return wechatUserList.isEmpty() ? null : wechatUserList.get(0);
	}

	/**
	 * 新增微信用户
	 *
	 * @param [wechatUser]
	 *            微信用户
	 * @return java.lang.Integer
	 */

	public Integer insertWechatUser(User wechatUser) {
		Preconditions.checkNotNull(wechatUser);
		Preconditions.checkNotNull(wechatUser.getOpenid(), ResultCode.OPENID_NULL.getDesc());
		userMapper.insertSelective(wechatUser);
		return wechatUser.getId();
	}

	/**
	 * 查询微信用户列表
	 *
	 * WechatUserQO
	 * 
	 * @return java.util.List<WechatUser>
	 * @param [record]
	 */
	@Cacheable
	public List<User> listWechatUsers(WechatUserQO record) {
		Preconditions.checkNotNull(record);
		UserExample example = new UserExample();
		final UserExample.Criteria criteria = example.createCriteria();
		Optional.ofNullable(record.getNickname()).ifPresent(s -> criteria.andNicknameLike("%" + s + "%"));
		Optional.ofNullable(record.getSex()).ifPresent(criteria::andSexEqualTo);
		return userMapper.selectByExample(example);
	}

	public double getActualPrice(Integer levelId) {
		ProdPriceStrategy strategy = ProdPriceStrategyMapping.mappingStrategy(levelId);
		return strategy.getActualPrice(200);
	}
}
